package winOrDie.Util;
/**
 * 
 */


import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.xerces.dom.DOMImplementationImpl;
import org.apache.xerces.jaxp.DocumentBuilderFactoryImpl;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;


public class XML_Manager 
{
	public Document createNewDocument() throws Exception
	{
		DOMImplementation domImplementation = new DOMImplementationImpl();
		Document document = domImplementation.createDocument(null, "root", null);
		return document;
		
	}
	
	


	public Document createNewDocument(String filename) throws Exception
	{
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		DOMImplementation impl = builder.getDOMImplementation();

		Document doc = impl.createDocument(filename, null, null);

		return doc;
	}
	
	

	public void saveXMLElementToFile(Element element, String filename) throws Exception
	{
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		transformerFactory.setAttribute("indent-number", new Integer(2));
		
		Transformer transformer = transformerFactory.newTransformer();
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		
		
		//DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
		//DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
		Document document = element.getOwnerDocument();
		document.replaceChild(element, document.getFirstChild());
		
		//document.appendChild(element);
		
		DOMSource source = new DOMSource(document);

		StreamResult streamResult = new StreamResult(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
		
		transformer.transform(source, streamResult);
	}
	
	
	
	public String getContentValueOfElement(Element element)
	{
		String the_value = new String();
		
		if (element.hasChildNodes())
		{
			NodeList NodeElementText = element.getChildNodes();
			the_value = ((Node)NodeElementText.item(0)).getNodeValue().trim();
		}
		
		return the_value;
	}
	
	public String getValueofElementNode(String Nodename, Element element)
	{
		String the_value = new String();
		
		NodeList myNodeList = element.getElementsByTagName(Nodename);

		if (myNodeList.getLength() > 0)
		{
			Element NodeElement = (Element)myNodeList.item(0);
			the_value = getContentValueOfElement(NodeElement);
		}
		return the_value;
	}
	
	public Document Load_File_into_XML_Document(String my_file_url) throws Exception
	{
		Document document = null;
		File inputFile = new File(my_file_url);
		
		if (!inputFile.exists())
		{
			Exception exception = new Exception("Fichero " + inputFile + " no existe.");
			throw exception;
		
		}
		
		DOMParser domParser = new DOMParser();
		domParser.parse(inputFile.getAbsolutePath());
		document = domParser.getDocument();
		return document;
		
		
	}
	

	public Document Load_File_into_XML_Document_old(String my_file_url)
	{
		Document my_document = null; // At the beginning is null

		DocumentBuilderFactory factory = DocumentBuilderFactoryImpl.newInstance();
		factory.setValidating(false);
		factory.setNamespaceAware(false);
		
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			
			builder.setErrorHandler(
					new ErrorHandler() {
						// ignore fatal errors (an exception is guaranteed)
						public void fatalError(SAXParseException exception)
						throws SAXException {
						}

						// treat validation errors as fatal
						public void error(SAXParseException e)
						throws SAXParseException
						{
							throw e;
						}

						// dump warnings too
						public void warning(SAXParseException err)
						throws SAXParseException
						{
							System.out.println("** Warning"
									+ ", line " + err.getLineNumber()
									+ ", uri " + err.getSystemId());
							System.out.println("   " + err.getMessage());
						}

					}
			); 
			my_document = builder.parse(new File(my_file_url));

		} catch (SAXException sxe) {
			// Error generated during parsing
			Exception  x = sxe;
			if (sxe.getException() != null)
				x = sxe.getException();
			x.printStackTrace();

		} catch (ParserConfigurationException pce) {
			// Parser with specified options can't be built
			pce.printStackTrace();

		} catch (IOException ioe) {
			// I/O error
			ioe.printStackTrace();
		}

		return my_document;
	}
	

	
	
	public class XMLfilter extends javax.swing.filechooser.FileFilter {
	    public boolean accept(File f) {
	        return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");
	    }
	    
	    public String getDescription() {
	        return "XML files";
	    }
	    
	}
	
	
	public XMLfilter getNewXMLfilter()
	{

		return new XML_Manager().new XMLfilter();
	}
	
	
	
	
	
	
	
	public static class DOM_AND_STRINGS
	{
		
		public static Document ParseStringToXmlDocument(String xml_String) throws SAXException, IOException, ParserConfigurationException
		{   
			InputSource is = null;	   
			//IMPORTANTE PARA PARSEAR STRINGS A DOCUMENT XML
			is = new InputSource(new CharArrayReader(xml_String.toCharArray()));

			DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
			Document doc = docBuilder.parse(is);

			return doc;
		}
		
		
		public static String ParseXmlDocumentToString(Document XmlDoc) throws TransformerException
		{
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "no");

			//initialize StreamResult with File object to save to file
			StreamResult result = new StreamResult(new StringWriter());
			DOMSource source = new DOMSource(XmlDoc);
			transformer.transform(source, result);

			String xmlString = result.getWriter().toString();

			return xmlString;		   
		}
		
		
		public static String DOM2String(Document doc) throws Exception
		{ 
		    TransformerFactory transformerFactory =TransformerFactory.newInstance(); 
		    Transformer transformer = null; 
		    try{ 
		        transformer = transformerFactory.newTransformer(); 
		    }catch (javax.xml.transform.TransformerConfigurationException error){ 
//		        coderror=123; 
		        String msgerror=error.getMessage();
		        throw new Exception(msgerror);
//		        return null; 
		    } 
		 
		    Source source = new DOMSource(doc); 
		 
		    StringWriter writer = new StringWriter(); 
		    Result result = new StreamResult(writer); 
		    try{ 
		        transformer.transform(source,result); 
		    }catch (javax.xml.transform.TransformerException error){ 
//		        coderror=123; 
		        String msgerror=error.getMessage();
		        throw new Exception(msgerror);
//		        return null; 
		    } 
		 
		    String s = writer.toString(); 
		    return s; 
		} 
		 
		public static Document string2DOM(String s) throws Exception
		{ 
		    Document tmpX=null; 
		    DocumentBuilder builder = null; 
		    try{ 
		        builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); 
		    }catch(javax.xml.parsers.ParserConfigurationException error){ 
//		        coderror=10; 
		        String msgerror="Error crando factory String2DOM "+error.getMessage();
		        return null; 
		    } 
		    try{ 
		        tmpX=builder.parse(new ByteArrayInputStream(s.getBytes())); 
		    }catch(org.xml.sax.SAXException error){ 
//		        coderror=10; 
		    	String msgerror="Error parseo SAX String2DOM "+error.getMessage(); 
		    	throw new Exception(msgerror);
//		        return null; 
		    }catch(IOException error){ 
//		        coderror=10; 
		        String msgerror="Error generando Bytes String2DOM "+error.getMessage();
		        throw new Exception(msgerror);
//		        return null; 
		    } 
		    return tmpX; 
		} 
	}
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

	
}